/*
 * @Author: c
 * @Date: 2023-12-26 12:14:46
 * @LastEditTime: 2024-01-17 05:23:08
 * @LastEditors: c
 * @Description: 
 * @FilePath: \music-web-backend\src\core\system\dict\dict.service.ts
 * https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { plainToClass } from 'class-transformer';
import { EXCEPTION } from 'src/common/const/constants';
import { IOption } from 'src/common/dto/option.dto';
import { PageResDto } from 'src/common/dto/page.dto';
import { CommonException } from 'src/common/exception/common.exception';
import { DataSource, Repository } from 'typeorm';
import { DictType } from '../dict_type/entities/dict_type.entity';
import { DictForm } from './dto/create-dict.dto';
import { DictPageQuery } from './dto/search-dict.dto';
import { Dict } from './entities/dict.entity';
import { DictTypeVo } from './vo/DictTypeVo';

@Injectable()
export class DictService {


  constructor(
    @InjectRepository(Dict) private dictRepository: Repository<Dict>,
    @InjectRepository(DictType) private dictTypeRepository: Repository<DictType>,
    private dataSource: DataSource
  ) { }


  async listDictOptions(typeCode: any): Promise<IOption<string, string>[]> {
    const dictList: Dict[] = await this.dictRepository.find({ where: { typeCode: typeCode } })
    return dictList.map(d => ({ label: d.name, value: d.value }))
  }


  /**
   * 字典-分页查询
   * @param queryParams 
   */
  async getDictPage({ name, typeCode, pageNum, pageSize }: DictPageQuery): Promise<PageResDto<DictTypeVo>> {

    const builder = this.dictRepository.createQueryBuilder('dict')
      .andWhere("dict.type_code = :typeCode", { typeCode })
    // .select(['id', 'name', "value", "status"])

    if (name) {
      builder.andWhere('dict.name like :name', { name })
    }

    const total = await builder.getCount()
    const dicts = await builder.offset((pageNum - 1) * pageSize).limit(pageSize).getMany();
    const dictVos = plainToClass(DictTypeVo, dicts)
    return PageResDto.result(dictVos, total)
  }


  /**
   * 字典-所有类型-新增
   * @param createDictDto 
   * @returns 
   */
  async create(createDictDto: DictForm): Promise<Dict> {
    const entity = plainToClass(Dict, createDictDto)
    return this.dictRepository.save(entity)
  }


  /**
 * 字典-所有类型-查询单条数据
 * @param id 
 * @returns 
 */
  findOne(id: number) {

    return this.dictRepository.findOneBy({ id })
  }

  /**
   *  字典-所有类型-修改单条数据
   * @param id 
   * @param updateDictDto 
   * @returns 
   */

  async update(id: number, updateDictDto: DictForm) {

    
   return   await this.dictRepository.createQueryBuilder()
        .update()
        .set(updateDictDto)
        .where("id = :id", { id })
        .execute();
  

    
  }

  /**
 * 字典-所有类型-根据ID删除单条数据
 * @param ids
 * @returns 
 */
  async removeByIds(ids: string) {
    const idArr = ids.split(",");

    const queryRunner = await this.dataSource.createQueryRunner();
    queryRunner.connect();
    await queryRunner.startTransaction()
    try {
      for await (const id of idArr) {

        queryRunner.manager
          .createQueryBuilder()
          .delete()
          .from(Dict)
          .where("id = :id", { id: +id })
          .execute();
      }
      await queryRunner.commitTransaction()
    } catch (error) {
      await queryRunner.rollbackTransaction()
      throw new CommonException(EXCEPTION.COMMON)
    } finally {
      await queryRunner.release()
    }


  }



  async remove(id: number) {

    return await this.dictRepository.delete({ id })

  }
}
